import React, { useState, useEffect } from 'react';
import { 
  View, 
  Text, 
  StyleSheet, 
  Switch, 
  TouchableOpacity, 
  Alert,
  ScrollView
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import AsyncStorage from '@react-native-async-storage/async-storage';

const SettingsScreen = () => {
  const [settings, setSettings] = useState({
    useLocation: true,
    defaultCity: '北京',
    temperatureUnit: 'celsius', // 'celsius' 或 'fahrenheit'
    notificationsEnabled: true,
    darkMode: false,
    autoRefresh: true
  });

  // 加载设置
  useEffect(() => {
    const loadSettings = async () => {
      try {
        const savedSettings = await AsyncStorage.getItem('weatherAppSettings');
        if (savedSettings) {
          setSettings(JSON.parse(savedSettings));
        }
      } catch (error) {
        console.error('加载设置失败:', error);
      }
    };
    
    loadSettings();
  }, []);

  // 保存设置
  const saveSettings = async (newSettings) => {
    try {
      const settingsToSave = { ...settings, ...newSettings };
      await AsyncStorage.setItem('weatherAppSettings', JSON.stringify(settingsToSave));
      setSettings(settingsToSave);
    } catch (error) {
      console.error('保存设置失败:', error);
      Alert.alert('错误', '保存设置失败');
    }
  };

  // 切换开关设置
  const toggleSetting = (key) => {
    saveSettings({ [key]: !settings[key] });
  };

  // 切换温度单位
  const toggleTemperatureUnit = () => {
    const newUnit = settings.temperatureUnit === 'celsius' ? 'fahrenheit' : 'celsius';
    saveSettings({ temperatureUnit: newUnit });
  };

  // 修改默认城市
  const changeDefaultCity = () => {
    // 这里可以导航到城市选择页面，或者显示一个输入对话框
    Alert.alert(
      '设置默认城市',
      '此功能将在未来版本中实现',
      [{ text: '确定', onPress: () => console.log('OK Pressed') }]
    );
  };

  // 清除缓存
  const clearCache = () => {
    Alert.alert(
      '清除缓存',
      '确定要清除所有缓存数据吗？',
      [
        { text: '取消', style: 'cancel' },
        { 
          text: '确定', 
          style: 'destructive',
          onPress: async () => {
            try {
              // 清除天气数据缓存，但保留设置
              const keys = await AsyncStorage.getAllKeys();
              const keysToRemove = keys.filter(key => key !== 'weatherAppSettings');
              await AsyncStorage.multiRemove(keysToRemove);
              Alert.alert('成功', '缓存已清除');
            } catch (error) {
              console.error('清除缓存失败:', error);
              Alert.alert('错误', '清除缓存失败');
            }
          }
        }
      ]
    );
  };

  // 关于应用
  const showAbout = () => {
    Alert.alert(
      '关于天气预报APP',
      '版本: 1.0.0\n开发者: CodeBuddy\n\n基于和风天气API提供的数据',
      [{ text: '确定' }]
    );
  };

  return (
    <ScrollView style={styles.container}>
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>常规设置</Text>
        
        <View style={styles.settingItem}>
          <View style={styles.settingTextContainer}>
            <Text style={styles.settingLabel}>使用定位服务</Text>
            <Text style={styles.settingDescription}>自动获取当前位置的天气</Text>
          </View>
          <Switch
            value={settings.useLocation}
            onValueChange={() => toggleSetting('useLocation')}
            trackColor={{ false: '#d0d0d0', true: '#81b0ff' }}
            thumbColor={settings.useLocation ? '#0080ff' : '#f4f3f4'}
          />
        </View>
        
        <TouchableOpacity style={styles.settingItem} onPress={changeDefaultCity}>
          <View style={styles.settingTextContainer}>
            <Text style={styles.settingLabel}>默认城市</Text>
            <Text style={styles.settingDescription}>当无法获取位置时使用</Text>
          </View>
          <View style={styles.settingValueContainer}>
            <Text style={styles.settingValue}>{settings.defaultCity}</Text>
            <Ionicons name="chevron-forward" size={20} color="#999" />
          </View>
        </TouchableOpacity>
        
        <TouchableOpacity style={styles.settingItem} onPress={toggleTemperatureUnit}>
          <View style={styles.settingTextContainer}>
            <Text style={styles.settingLabel}>温度单位</Text>
            <Text style={styles.settingDescription}>选择摄氏度或华氏度</Text>
          </View>
          <View style={styles.settingValueContainer}>
            <Text style={styles.settingValue}>
              {settings.temperatureUnit === 'celsius' ? '摄氏度 (°C)' : '华氏度 (°F)'}
            </Text>
            <Ionicons name="chevron-forward" size={20} color="#999" />
          </View>
        </TouchableOpacity>
      </View>
      
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>通知与更新</Text>
        
        <View style={styles.settingItem}>
          <View style={styles.settingTextContainer}>
            <Text style={styles.settingLabel}>天气通知</Text>
            <Text style={styles.settingDescription}>接收天气预警和提醒</Text>
          </View>
          <Switch
            value={settings.notificationsEnabled}
            onValueChange={() => toggleSetting('notificationsEnabled')}
            trackColor={{ false: '#d0d0d0', true: '#81b0ff' }}
            thumbColor={settings.notificationsEnabled ? '#0080ff' : '#f4f3f4'}
          />
        </View>
        
        <View style={styles.settingItem}>
          <View style={styles.settingTextContainer}>
            <Text style={styles.settingLabel}>自动刷新</Text>
            <Text style={styles.settingDescription}>定期更新天气数据</Text>
          </View>
          <Switch
            value={settings.autoRefresh}
            onValueChange={() => toggleSetting('autoRefresh')}
            trackColor={{ false: '#d0d0d0', true: '#81b0ff' }}
            thumbColor={settings.autoRefresh ? '#0080ff' : '#f4f3f4'}
          />
        </View>
      </View>
      
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>外观</Text>
        
        <View style={styles.settingItem}>
          <View style={styles.settingTextContainer}>
            <Text style={styles.settingLabel}>深色模式</Text>
            <Text style={styles.settingDescription}>使用深色主题</Text>
          </View>
          <Switch
            value={settings.darkMode}
            onValueChange={() => toggleSetting('darkMode')}
            trackColor={{ false: '#d0d0d0', true: '#81b0ff' }}
            thumbColor={settings.darkMode ? '#0080ff' : '#f4f3f4'}
          />
        </View>
      </View>
      
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>数据与存储</Text>
        
        <TouchableOpacity style={styles.settingItem} onPress={clearCache}>
          <View style={styles.settingTextContainer}>
            <Text style={styles.settingLabel}>清除缓存</Text>
            <Text style={styles.settingDescription}>删除所有缓存的天气数据</Text>
          </View>
          <Ionicons name="trash-outline" size={20} color="#ff6b6b" />
        </TouchableOpacity>
      </View>
      
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>关于</Text>
        
        <TouchableOpacity style={styles.settingItem} onPress={showAbout}>
          <View style={styles.settingTextContainer}>
            <Text style={styles.settingLabel}>关于天气预报APP</Text>
            <Text style={styles.settingDescription}>版本信息和开发者</Text>
          </View>
          <Ionicons name="information-circle-outline" size={20} color="#999" />
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  section: {
    marginTop: 20,
    backgroundColor: '#fff',
    borderRadius: 10,
    marginHorizontal: 15,
    overflow: 'hidden',
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
    paddingHorizontal: 15,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  settingItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 12,
    paddingHorizontal: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  settingTextContainer: {
    flex: 1,
  },
  settingLabel: {
    fontSize: 16,
    color: '#333',
  },
  settingDescription: {
    fontSize: 14,
    color: '#999',
    marginTop: 2,
  },
  settingValueContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  settingValue: {
    fontSize: 14,
    color: '#666',
    marginRight: 5,
  },
});

export default SettingsScreen;